<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

 
    <script>

      const queueFn = (emitNumber)=> {
        
        let current = 0 // 当前计数
        let queue = [] // 待执行队列
        let maxNumber = emitNumber||4 // 最大并发数量


        const exeQueue = () => {

                while(current < maxNumber &&  queue.length) {
                    console.log(11);
                    current += 1
                    const p = queue.shift() // 取前面入栈的
                    p()
                    .finally(()=> {
                        current -= 1
                        exeQueue()
                    })
                }

        }

        return (promiseFn)=> {
                    queue.push(promiseFn)
                    exeQueue()
                }
        
      }

      const exeQueue = queueFn(4)

      function fn(delay){
        return () => {
        return new Promise((resolve, reject) =>{
            setTimeout(()=> {
                console.log('执行');
                resolve()
            },delay)
        }).then(()=> {
            console.log('成功',delay);
        })
    }

      }

      exeQueue(fn(1000))
      exeQueue(fn(2000))
      exeQueue(fn(3000))
      
    </script>
</body>

</html>